/*
 * Copyright 2013 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.yunos.tv.common.util;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类CookieUtil.java的实现描述：TODO 类实现描述
 * @author riqi 2013-7-1 上午11:33:40
 */
public class CookieUtil {

    /**
     * 设置cookie
     * @param response
     * @param name
     * @param value
     * @param path
     * @param maxExp
     */
    public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge, String domain, boolean httpOnly) {
        String httpOnlyString = "";
        String maxAgeString = "";
        if (true == httpOnly) {
            httpOnlyString = ";HttpOnly";
        }

        if (maxAge >= 0) {
            maxAgeString = ";Max-Age=" + maxAge;
        }
        response.addHeader("Set-Cookie", name + "=" + value + ";Path=" + path + ";Domain=" + domain + maxAgeString + httpOnlyString);
    }

    /**
     * 删除cookie
     * @param response
     * @param name
     */
    public static void delCookie(HttpServletResponse response, String name, String domain) {
        CookieUtil.setCookie(response, name, "", "/", 0, domain, true);
    }

    /**
     * 获取Cookie
     * @param request
     * @param name
     * @return
     */
    public static Map<String, String> getCookie(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            map.put(cookie.getName(), cookie.getValue());
        }
        return map;
    }
}